#include<iostream>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>


class UdpClient
{
public:
    bool InitClinet()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cerr << "socket create error" << std::endl;
            return false;
        }
        return true;
    }

    UdpClient(std::string server_ip, int server_port)
    :_sockfd(-1)
    ,_server_port(server_port)
    ,_server_ip(server_ip)
    {}

    ~UdpClient()
    {
        if(_sockfd >= 0)
        {
            close(_sockfd);
        }
    }

    // void Start()
    // {
    //     std::string msg;
    //     struct sockaddr_in peer;
    //     memset(&peer, '\0', sizeof(peer));
    //     peer.sin_family = AF_INET;
    //     peer.sin_port = htons(_server_port);
    //     peer.sin_addr.s_addr = inet_addr(_server_ip.c_str());

    //     for(;;)
    //     {
    //         std:: cout << "Please Enter# ";
    //         getline(std::cin, msg);
    //         sendto(_sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr*)&peer, sizeof(peer));

    //     }
    // }

//回声服务器版本
void Start()
{
    std::string msg;
    struct sockaddr_in peer;
    memset(&peer, '\0', sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = htons(_server_port);
    peer.sin_addr.s_addr = inet_addr(_server_ip.c_str());

    for(;;)
    {
        std::cout << "Please Enter# ";
        getline(std::cin, msg);
        sendto(_sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr*)&peer, sizeof(peer));

#define SIZE 128
        char buffer[SIZE];
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t size = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&tmp, &len);
        if(size > 0)
        {
            buffer[size] = '\0';
            std::cout << buffer << std::endl;
        }
    }
}
private:
    int _sockfd;//文件描述符
    int _server_port;//服务端端口号
    std::string _server_ip; //服务端IP地址  
};

int main(int argc, char* argv[])
{
    if(argc!= 3)
    {
        std::cerr << "Usage " << argv[0] << "server_ip server_port" << std::endl;
        return 1;
    }

    std::string server_ip = argv[1];
    int server_port = atoi(argv[2]);
    UdpClient* clt = new UdpClient(server_ip, server_port);
    clt->InitClinet();
    clt->Start();
    return 0;
}
